package com.anxinr.interceptor;

import cn.hutool.crypto.digest.MD5;
import com.anxinr.constant.RedisConstant;
import com.anxinr.enums.ExceptionEnum;
import com.anxinr.exception.LogicException;
import com.anxinr.util.JWTUtils;
import com.anxinr.util.RedisUtil;
import com.anxinr.util.UserInfoContext;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器拦截处理方式
 *
 * @author anxinr
 */
@Slf4j
@Component
public class StudyInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil ;
    @Autowired
    private UserInfoContext userInfoContext ;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        try {
            /**查看是否登录*/
            String token = request.getHeader("token");
            if (StringUtils.isBlank(token)) {
                throw new LogicException(ExceptionEnum.STUDY_USER_NAME_ERROR);
            }
            /**把用户信息存入ThreadLocal中*/
            userInfoContext.setUserInfo(redisUtil.getUserInfo(RedisConstant.USER_TOKEN_INFO + token));
        }catch (Exception e){
            log.info("捕抓到位置异常，异常信息 -> {}",e.getMessage());
            throw e ;
        }
        return true;
    }
}
